const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const config = require('../config/env');

// 从配置获取JWT密钥
const JWT_SECRET = config.JWT_SECRET;
const JWT_EXPIRES_IN = config.JWT_EXPIRES_IN;

// 登录
exports.login = async (req, res) => {
  try {
    console.log('登录请求:', req.body);
    const { username, password } = req.body;

    // 验证请求数据
    if (!username || !password) {
      console.log('登录失败: 缺少用户名或密码');
      return res.status(400).json({
        status: 'error',
        message: '请提供用户名和密码'
      });
    }

    // 查询用户，不包括复杂关系
    const user = await prisma.user.findUnique({
      where: { username }
    });

    // 如果用户不存在
    if (!user) {
      console.log('登录失败: 用户不存在');
      return res.status(401).json({
        status: 'error',
        message: '用户名或密码错误'
      });
    }

    // 如果用户被禁用
    if (!user.status) {
      console.log('登录失败: 用户已被禁用');
      return res.status(401).json({
        status: 'error',
        message: '用户已被禁用，请联系管理员'
      });
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      console.log('登录失败: 密码错误');
      return res.status(401).json({
        status: 'error',
        message: '用户名或密码错误'
      });
    }

    // 单独查询角色
    const role = await prisma.Role.findUnique({
      where: { id: user.roleId }
    });

    // 单独查询部门
    let department = null;
    if (user.departmentId) {
      department = await prisma.Department.findUnique({
        where: { id: user.departmentId }
      });
    }

    // 查询用户权限 - 避免使用嵌套include
    const rolePermissions = await prisma.RolePermission.findMany({
      where: { roleId: user.roleId }
    });
    
    // 获取权限ID列表
    const permissionIds = rolePermissions.map(rp => rp.permissionId);
    
    // 单独查询权限详情
    const permissionDetails = await prisma.Permission.findMany({
      where: {
        id: {
          in: permissionIds
        }
      }
    });

    // 提取权限信息
    const permissions = permissionDetails.map(p => ({
      code: p.code,
      name: p.name,
      group: p.group
    }));

    // 生成JWT令牌
    const token = jwt.sign(
      { 
        id: user.id, 
        username: user.username,
        roleId: user.roleId,
        departmentId: user.departmentId
      },
      JWT_SECRET,
      { expiresIn: JWT_EXPIRES_IN }
    );

    console.log('登录成功:', user.username);

    // 返回用户信息和令牌
    res.json({
      status: 'success',
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        name: user.name,
        role: role ? {
          id: role.id,
          name: role.name,
          description: role.description
        } : null,
        department: department ? {
          id: department.id,
          name: department.name
        } : null,
        permissions: permissions
      }
    });
  } catch (error) {
    console.error('登录处理错误:', error);
    res.status(500).json({
      status: 'error',
      message: '登录身份验证失败',
      error: error.message
    });
  }
};

// 获取当前用户信息
exports.getCurrentUser = async (req, res) => {
  try {
    // 用户信息已在认证中间件中添加到req对象，但只包含基本信息
    // 需要查询详细信息，包括角色、权限和部门
    const userId = req.user.id;
    
    const user = await prisma.user.findUnique({
      where: { id: userId }
    });
    
    if (!user) {
      return res.status(404).json({
        status: 'error',
        message: '用户不存在'
      });
    }
    
    // 单独查询角色
    const role = await prisma.Role.findUnique({
      where: { id: user.roleId }
    });
    
    // 单独查询部门
    let department = null;
    if (user.departmentId) {
      department = await prisma.Department.findUnique({
        where: { id: user.departmentId }
      });
    }
    
    // 查询用户权限 - 避免使用嵌套include
    const rolePermissions = await prisma.RolePermission.findMany({
      where: { roleId: user.roleId }
    });
    
    // 获取权限ID列表
    const permissionIds = rolePermissions.map(rp => rp.permissionId);
    
    // 单独查询权限详情
    const permissionDetails = await prisma.Permission.findMany({
      where: {
        id: {
          in: permissionIds
        }
      }
    });

    // 提取权限信息
    const permissions = permissionDetails.map(p => ({
      code: p.code,
      name: p.name,
      group: p.group
    }));
    
    res.json({
      status: 'success',
      data: {
        id: user.id,
        username: user.username,
        name: user.name,
        role: {
          id: role.id,
          name: role.name,
          description: role.description
        },
        department: department ? {
          id: department.id,
          name: department.name
        } : null,
        permissions: permissions
      }
    });
  } catch (error) {
    console.error('获取当前用户信息错误:', error);
    res.status(500).json({
      status: 'error',
      message: '服务器内部错误',
      error: error.message
    });
  }
};

// 登出（仅作为API端点，实际的登出在客户端处理）
exports.logout = (req, res) => {
  res.json({
    status: 'success',
    message: '登出成功'
  });
};

// 刷新令牌
exports.refreshToken = async (req, res) => {
  try {
    const { token } = req.body;
    
    if (!token) {
      return res.status(400).json({
        status: 'error',
        message: '缺少令牌'
      });
    }
    
    try {
      // 验证令牌
      const decoded = jwt.verify(token, JWT_SECRET);
      
      // 查询用户
      const user = await prisma.user.findUnique({
        where: { id: decoded.id }
      });
      
      if (!user || !user.status) {
        return res.status(401).json({
          status: 'error',
          message: '无效的令牌或用户已被禁用'
        });
      }
      
      // 单独查询角色
      const role = await prisma.Role.findUnique({
        where: { id: user.roleId }
      });
      
      // 单独查询部门
      let department = null;
      if (user.departmentId) {
        department = await prisma.Department.findUnique({
          where: { id: user.departmentId }
        });
      }
      
      // 查询用户权限 - 避免使用嵌套include
      const rolePermissions = await prisma.RolePermission.findMany({
        where: { roleId: user.roleId }
      });
      
      // 获取权限ID列表
      const permissionIds = rolePermissions.map(rp => rp.permissionId);
      
      // 单独查询权限详情
      const permissionDetails = await prisma.Permission.findMany({
        where: {
          id: {
            in: permissionIds
          }
        }
      });

      // 提取权限信息
      const permissions = permissionDetails.map(p => ({
        code: p.code,
        name: p.name,
        group: p.group
      }));
      
      // 生成新的JWT令牌
      const newToken = jwt.sign(
        { 
          id: user.id, 
          username: user.username,
          roleId: user.roleId,
          departmentId: user.departmentId
        },
        JWT_SECRET,
        { expiresIn: JWT_EXPIRES_IN }
      );
      
      res.json({
        status: 'success',
        message: '令牌刷新成功',
        token: newToken,
        user: {
          id: user.id,
          username: user.username,
          name: user.name,
          role: {
            id: role.id,
            name: role.name,
            description: role.description
          },
          department: department ? {
            id: department.id,
            name: department.name
          } : null,
          permissions: permissions
        }
      });
    } catch (error) {
      return res.status(401).json({
        status: 'error',
        message: '无效的令牌',
        error: error.message
      });
    }
  } catch (error) {
    console.error('令牌刷新错误:', error);
    res.status(500).json({
      status: 'error',
      message: '服务器内部错误',
      error: error.message
    });
  }
}; 